<template>
  <div class="tenant-management-page">
    <!-- 筛选及搜索区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <!-- 查询表单区域，占满一行 -->
        <el-col :span="24">
          <el-form :inline="true" :model="filterForm" ref="filterForm">
            <el-form-item label="租户类型">
              <el-select v-model="filterForm.type" placeholder="全部" clearable>
                <el-option
                  v-for="item in typeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="filterForm.tenantStatus"
                placeholder="全部"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="租户搜索">
              <el-input
                v-model="filterForm.searchKey"
                placeholder="输入公司名"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- 新增用户按钮区域，单独占一行 -->
        <el-col :span="24" style="text-align: left; margin-top: 12px">
          <el-button type="primary" @click="handleAddTenant"
            >新增租户</el-button
          >
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
      :border="false"
    >
      <el-table-column label="序号" width="40" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="tenantName"
        label="租户"
        min-width="80"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.tenantName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" min-width="80" align="center">
        <template #default="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="tenantStatus"
        label="状态"
        min-width="80"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.tenantStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="contactsPhone"
        label="联系电话"
        min-width="100"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.contactsPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="contactsEmail"
        label="联系邮箱"
        min-width="100"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.contactsEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="contactsName"
        label="联系人"
        min-width="80"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.contactsName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="开户日期"
        min-width="130"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.createdTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="validityTime"
        label="租户有效期"
        min-width="130"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.validityTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="industry"
        label="行业"
        min-width="80"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.industry }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="330" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="text"
            style="color: red"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>

    <!-- 新增租户弹窗（完整实现） -->
    <el-dialog
      title="租户信息"
      :visible.sync="addTenantDialogVisible"
      width="600px"
      :before-close="handleAddTenantDialogClose"
    >
      <el-form :model="addTenantForm" label-width="100px" ref="addForm">
        <el-form-item label="租户名" required>
          <el-input v-model="addTenantForm.tenantName"></el-input>
        </el-form-item>
        <el-form-item label="租户类型" required>
          <el-select
            v-model="addTenantForm.type"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select
            v-model="addTenantForm.tenantStatus"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="法人代表" required>
          <el-input v-model="addTenantForm.legalRepresentative"></el-input>
        </el-form-item>
        <el-form-item label="联系人职位" required>
          <el-input v-model="addTenantForm.contactsPosition"></el-input>
        </el-form-item>
        <el-form-item label="机构编码" required>
          <el-input v-model="addTenantForm.orgName"></el-input>
        </el-form-item>
      
        <el-form-item label="统一社会信用代码" required>
          <el-input v-model="addTenantForm.socialCreditCode"></el-input>
        </el-form-item>

        <el-form-item label="联系人" required>
          <el-input v-model="addTenantForm.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="addTenantForm.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" required>
          <el-input v-model="addTenantForm.contactsEmail"></el-input>
        </el-form-item>
        <el-form-item label="联系地址" required>
          <el-input v-model="addTenantForm.address"></el-input>
        </el-form-item>
  
        <el-form-item label="开户日期" required>
          <el-date-picker
            v-model="addTenantForm.createdTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="租户有效期" required>
          <el-date-picker
            v-model="addTenantForm.validityTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="行业" required>
          <el-input v-model="addTenantForm.industry"></el-input>
        </el-form-item>
        <el-form-item label="企业传真" required>
          <el-input v-model="addTenantForm.faxNumber"></el-input>
        </el-form-item>
        <el-form-item label="企业介绍">
          <el-input
            type="textarea"
            v-model="addTenantForm.introduction"
          ></el-input>
        </el-form-item>
        <!-- 补充营业执照上传字段（仿照头像逻辑） -->
      <el-form-item label="营业执照" required>
        <el-upload
          class="license-upload"
          ref="licenseUpload"
          :action="upLoadParam.url" 
          :headers="{ token: upLoadParam.token }"  
          :file-list="licenseFileList" 
          :auto-upload="true"  
          :on-success="handleLicenseUploadSuccess" 
          :on-change="handleLicenseFileChange" 
          :on-remove="handleLicenseRemove"  
          :limit="1" 
          accept=".jpg,.png,.pdf" 
        >
          <el-button size="small" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">支持jpg、png、pdf格式，大小不超过10MB</div>
        </el-upload>
      </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddTenantDialogClose">取消</el-button>
          <el-button type="primary" @click="handleAddTenantConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗（可复用或调整） -->
    <el-dialog title="租户详情" :visible.sync="detailVisible" width="500px">
      <el-form label-width="120px">
        <el-form-item label="租户名">
          <el-input v-model="detailForm.tenantName" disabled></el-input>
        </el-form-item>
        <el-form-item label="租户类型">
          <el-input v-model="detailForm.type" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="detailForm.tenantStatus" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="detailForm.contactsPhone" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱">
          <el-input v-model="detailForm.contactsEmail" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="detailForm.contactsName" disabled></el-input>
        </el-form-item>
        <el-form-item label="开户日期">
          <el-input v-model="detailForm.createdTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="租户有效期">
          <el-input v-model="detailForm.validityTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="detailForm.industry" disabled></el-input>
        </el-form-item>

        <!-- 补充联系地址字段 -->
        <el-form-item label="联系地址">
          <el-input v-model="detailForm.address" disabled></el-input>
        </el-form-item>
        <!-- 补充企业传真字段 -->
        <el-form-item label="企业传真">
          <el-input v-model="detailForm.faxNumber" disabled></el-input>
        </el-form-item>
        <!-- 补充企业介绍字段 -->
        <el-form-item label="企业介绍">
          <el-input
            type="textarea"
            v-model="detailForm.introduction"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 编辑租户弹窗 -->
    <el-dialog
      title="编辑租户信息"
      :visible.sync="editDialogVisible"
      width="600px"
      :before-close="handleEditDialogClose"
    >
      <el-form :model="editTenantForm" label-width="100px" ref="editForm">
        <el-form-item label="租户名" required>
          <el-input v-model="editTenantForm.tenantName"></el-input>
        </el-form-item>
        <el-form-item label="租户类型" required>
          <el-select
            v-model="editTenantForm.type"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select
            v-model="editTenantForm.tenantStatus"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="editTenantForm.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" required>
          <el-input v-model="editTenantForm.contactsEmail"></el-input>
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="editTenantForm.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="开户日期" required>
          <el-date-picker
            v-model="editTenantForm.createdTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="租户有效期" required>
          <el-date-picker
            v-model="editTenantForm.validityTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="行业" required>
          <el-input v-model="editTenantForm.industry"></el-input>
        </el-form-item>
        <el-form-item label="联系地址" required>
          <el-input v-model="editTenantForm.address"></el-input>
        </el-form-item>
        <el-form-item label="企业传真" required>
          <el-input v-model="editTenantForm.faxNumber"></el-input>
        </el-form-item>
        <el-form-item label="企业介绍">
          <el-input
            type="textarea"
            v-model="editTenantForm.introduction"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getFeiShuUpLoadProjectParams } from "@/api/tenant";
export default {
  name: "TenantManagement",
  data() {
    return {
        upLoadParam: {}, // 飞书上传参数（与头像共用，包含url、token）
      licenseFileList: [], // 营业执照文件列表
      licenseUrl: "" ,// 营业执照上传后的存储地址（对应实体类的businessLicense字段）
      // 新增租户弹窗控制
      addTenantDialogVisible: false,
      // 新增表单数据（与编辑表单字段对应，补充完整SysTenant属性）
      addTenantForm: {
        legalRepresentative: "", // 法人代表字段
        contactsPosition: "", // 联系人职位字段
        tenantName: "",
        type: "",
        tenantStatus: "",
        orgName: "",
        legalRepresentative: "",
        socialCreditCode: "",
        businessLicense: "",
        greennessIntegral: 0,
        greennessLevel: 0,
        industry: "",
        validityDayNum: 0,
        telephone: "",
        address: "",
        faxNumber: "",
        remarks: "",
        contactsName: "",
        contactsPosition: "",
        contactsPhone: "",
        contactsEmail: "",
        introduction: "",
        createdTime: "",
        validityTime: "",
      },
      editDialogVisible: false,
      editTenantForm: {
        tenantName: "",
        type: "",
        tenantStatus: "",
        contactsPhone: "",
        contactsEmail: "",
        contactsName: "",
        createdTime: "",
        validityTime: "",
        industry: "",
        address: "",
        faxNumber: "",
        introduction: "",
      },
      // 筛选表单
      filterForm: {
        type: "",
        tenantStatus: "",
        searchKey: "",
      },
      // 下拉选项
      typeOptions: [], // 示例，可从接口获取
      statusOptions: [], // 示例，可从接口获取
      // 表格数据
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      // 弹窗相关
      addTenantDialogVisible: false,
      addTenantForm: {
        tenantName: "",
        type: "",
        tenantStatus: "",
        contactsPhone: "",
        contactsEmail: "",
        contactsName: "",
        createdTime: "",
        validityTime: "",
        industry: "",
      },
      detailVisible: false,
      detailForm: {},
    };
  },
  created() {
    this.fetchTableData();
    this.initTypeOptions();
  },
  mounted() {
    // 初始化飞书上传参数（与头像上传逻辑一致）
    this.upLoadParam = getFeiShuUpLoadProjectParams();
  },
  methods: {
     // 1. 营业执照文件选择/变更时触发（仅保留最后一个文件）
    handleLicenseFileChange(file, fileList) {
      this.licenseFileList = fileList.slice(-1); // 只保留最新选择的1个文件
    },
    
    // 2. 营业执照文件移除时触发（清空列表和地址）
    handleLicenseRemove(file, fileList) {
      this.licenseFileList = [];
      this.licenseUrl = ""; // 清空上传地址
    },
    
    // 3. 营业执照上传成功后触发（获取存储地址）
    handleLicenseUploadSuccess(response) {
      if (response && response.code === 200) {
        this.licenseUrl = response.msg; // 保存上传后的地址（与头像逻辑一致）
        this.$message.success("营业执照上传成功");
      } else {
        this.$message.error("营业执照上传失败，请重试");
      }
    },
    // 打开新增租户弹窗
    // 打开新增弹窗
    handleAddTenant() {
      // 重置表单
      this.addTenantForm = {
        tenantName: "",
        type: "",
        tenantStatus: "",
        orgName: "",
        legalRepresentative: "",
        socialCreditCode: "",
        businessLicense: "",
        greennessIntegral: 0,
        greennessLevel: 0,
        industry: "",
        validityDayNum: 0,
        telephone: "",
        address: "",
        faxNumber: "",
        remarks: "",
        contactsPosition: "", // 联系人职位字段
        legalRepresentative: "", // 法人代表字段
        contactsName: "",
        contactsPosition: "",
        contactsPhone: "",
        contactsEmail: "",
        introduction: "",
        createdTime: new Date(), // 默认当前日期
        validityTime: "",
         businessLicense: "" 
      };
       this.licenseFileList = [];
      this.licenseUrl = "";
      this.addTenantDialogVisible = true;
    },
    // 关闭新增弹窗
    handleAddTenantDialogClose() {
      this.addTenantDialogVisible = false;
    },
    // 确认新增
    async handleAddTenantConfirm() {
      try {
        if (this.licenseUrl) {
          this.addTenantForm.businessLicense = this.licenseUrl;
        }
        // 调用新增接口（与编辑接口风格一致）
        const res = await this.$request.post(
          "/system/sysTenant/add",
          this.addTenantForm
        );
        if (res.code === 200) {
          this.$message.success("新增租户成功");
          this.handleAddTenantDialogClose();
          this.fetchTableData(); // 刷新表格
        }
      } catch (error) {
        console.error("新增租户失败:", error);
        this.$message.error("新增失败，请重试");
      }
    },
    // 打开编辑弹窗
    handleEdit(row) {
      this.editTenantForm = { ...row };
      this.editDialogVisible = true;
    },
    // 关闭编辑弹窗（重置表单）
    handleEditDialogClose() {
      this.editTenantForm = {
        tenantName: "",
        type: "",
        tenantStatus: "",
        contactsPhone: "",
        contactsEmail: "",
        contactsName: "",
        createdTime: "",
        validityTime: "",
        industry: "",
        address: "",
        faxNumber: "",
        introduction: "",
      };
       // 清空上传相关
      this.licenseFileList = [];
      this.licenseUrl = "";
      this.editDialogVisible = false;
    },
    // 编辑确认提交
    async handleEditConfirm() {
      try {
        // 模拟接口提交，实际替换为真实编辑接口
        const res = await this.$request.put(
          "/system/sysTenant/update",
          this.editTenantForm
        );
        if (res.code === 200) {
          this.$message.success("编辑租户成功");
          this.handleEditDialogClose();
          this.fetchTableData(); // 刷新表格数据
        }
      } catch (error) {
        console.error("编辑租户失败:", error);
        this.$message.error("编辑失败，请重试");
      }
    },
    async fetchDeliveryOptions(type) {
      this.optionsLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(
          `/trade/carbonTradeQuote/getDeliveryMethod/${type}`
        );
        if (res.code == 200) {
          return res.data; // 返回查询到的列表
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },
    async initTypeOptions() {
      // 1. 获取状态
      const modes = await this.fetchDeliveryOptions("accountStatus");
      this.statusOptions = modes;
      // 2. 获取租户类型
      const places = await this.fetchDeliveryOptions("accountType");
      this.typeOptions = places;
    },
    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        // 模拟接口请求，实际替换为真实接口及参数
        const res = await this.$request.post("/system/sysTenant/getPageList", {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          ...this.filterForm,
        });
        if (res.code === 200) {
          console.log("res1", res);
          this.tableData = res.data.records;
          this.totalCount = Number(res.data.total);
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.tableLoading = false;
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },
    // 新增租户弹窗打开
    handleAddTenant() {
      this.addTenantDialogVisible = true;
    },
    // 新增租户弹窗关闭
    handleAddTenantDialogClose() {
      this.addTenantForm = {
        tenantName: "",
        type: "",
        tenantStatus: "",
        contactsPhone: "",
        contactsEmail: "",
        contactsName: "",
        createdTime: "",
        validityTime: "",
        industry: "",
      };
      this.addTenantDialogVisible = false;
    },

    // 查看详情
    handleView(row) {
      this.detailForm = { ...row };
      this.detailVisible = true;
    },
    // 编辑（可扩展编辑弹窗逻辑）
    // 删除（可扩展删除逻辑）
    handleDelete(row) {
      this.$confirm("此操作将永久删除该租户，是否继续?", "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            // 模拟接口删除，实际替换为真实接口
            const res = await this.$request.delete(
              `/system/sysTenant/delete/${row.id}`
            );
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请重试");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchTableData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },
  },
};
</script>

<style scoped>
.form-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.section-title {
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  color: #1890ff;
}

/* 弹窗底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.tenant-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-section {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  width: 100%;
}
</style>